/*
 * Copyright (c) jiucheng.org
 */
package org.jiucheng.agent;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.Instrumentation;
import java.util.Properties;

import org.jiucheng.instrument.ExtClassFileTransformer;

/**
 * <pre>
 * helloworld
 * + jiucheng-agent
 *   + lib
 *     + jiucheng-agent-*.jar
 *     + javassist-*.jar
 *   + conf
 *     + jiucheng-agent.properties
 *   + bin
 *   + log
 *     + localhost.2017-02-19.log
 *   + tmp
 *     +
 *   @author jiucheng [jiucheng.org@gmail.com]
 * </pre>
 */
public class Agent {
    
    private static Properties props;
    
    public static void premain(String args, Instrumentation inst) {
        loadProperties();
        if(getProp("version") == null) {
            return;
        }
        String classpath = getProp("webapp.classpath");
        if(classpath == null || classpath.trim().length() == 0) {
            return;
        }
        String packages = getProp("webapp.package");
        if(packages == null || packages.trim().length() == 0) {
            return;
        }
        inst.addTransformer(new ExtClassFileTransformer(classpath.split(","), packages.split(","), getProp("webapp.exception")));
    }
    
    public static String getProp(String key) {
        return props.getProperty(key);
    }
    
    // ../helloworld/jiucheng-agent/lib/jiucheng-agent-0.0.1-SNAPSHOT.jar
    private static void loadProperties() {
        props = new Properties();
        String path = Agent.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        path = path.substring(0, path.lastIndexOf("/lib/jiucheng-agent-") + 1);
        String file = path + "conf/jiucheng-agent.properties";
        try {
            InputStream is = new FileInputStream(file);
            props.load(is);
            props.put("webapp.dir", path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
